<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;

class Admin extends Model
{
    use HasFactory;

    protected $table = 'admin';

    /**
     * 指定哪些属性可以在使用 create() 或 update() 方法时被批量赋值
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'username',
        'account',
        'password',
        'roles',
        'status'
    ];

    /**
     * 隐藏字段
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
    ];

    /**
     * 默认情况下 $timestamps 为 true，表示启用自动管理
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 字段输出格式转换
     * @var string[]
     */
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];

    /**
     * 密码加密
     * @param $value
     * @return void
     */
    public function setPasswordAttribute($value): void
    {
        $this->attributes['password'] = Hash::make($value);
    }

    /**
     * 自定义访问器，将 roles 字段从字符串转换为数组
     * @param $value
     * @return array
     */
    public function getRolesAttribute($value): array
    {
        return $value !== null ? explode(',', $value) : [];
    }

    /**
     * 自定义修饰器，将 roles 字段从数组转换为字符串
     * @param $value
     * @return void
     */
    public function setRolesAttribute($value): void
    {
        $this->attributes['roles'] = is_array($value) ? implode(',', $value) : $value;
    }
}
